package com.lp.rpc.registry.watcher;

import com.lp.rpc.constants.LpConstant;
import com.lp.rpc.registry.LocalServiceCache;
import com.lp.rpc.registry.ZkConnection;
import com.lp.rpc.registry.ZkOperation;
import lombok.SneakyThrows;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NodeDataChangeWatcher implements Watcher {
    private static final ZooKeeper zooKeeper;

    static {
        zooKeeper = ZkConnection.connection();
    }

    @SneakyThrows
    @Override
    public void process(WatchedEvent watchedEvent) {
        List<String> children = zooKeeper.getChildren(LpConstant.ServiceRoot, true);
        Map<String,Object> map = new HashMap<>();
        for (String child : children) {
            String data = ZkOperation.getData(LpConstant.ServiceRoot + child);
            map.put(child, data);
            LocalServiceCache.remove(child);
        }
        LocalServiceCache.putBatch(map);
    }
}
